import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/models/attr_name.dart';
import 'package:merchants/models/attr_value.dart';
import 'package:merchants/models/attr_value_data.dart';
import 'package:merchants/services/attr_value.dart';
import 'package:merchants/providers/providers.dart';

class AttrValueManagementPage extends ConsumerStatefulWidget {
  final AttrName attrName;

  const AttrValueManagementPage({super.key, required this.attrName});

  @override
  ConsumerState<AttrValueManagementPage> createState() => _AttrValueManagementPageState();
}

class _AttrValueManagementPageState extends ConsumerState<AttrValueManagementPage> {
  late Future<List<AttrValue>> _attrValuesFuture;
  bool isAdding = false;
  bool isEditing = false;
  int? editingIndex;
  final TextEditingController _valueController = TextEditingController();

  @override
  void initState() {
    super.initState();
    print('DEBUG: AttrValueManagementPage initState 被调用');
    _attrValuesFuture = ref.read(attrValueServiceProvider).getListByAttrName(widget.attrName.id!);
    print('DEBUG: 规格值数据请求已发起');
  }

  @override
  void dispose() {
    _valueController.dispose();
    super.dispose();
  }

  void _refreshAttrValues() {
    setState(() {
      _attrValuesFuture = ref.read(attrValueServiceProvider).getListByAttrName(widget.attrName.id!);
      _valueController.clear();
    });
  }

  void _startAdding() {
    print('DEBUG: 添加规格值按钮被点击');
    setState(() {
      isAdding = true;
      _valueController.clear();
    });
    print('DEBUG: isAdding 设置为 true');
  }

  void _startEditing(int index, List<AttrValue> attrValues) {
    setState(() {
      isEditing = true;
      editingIndex = index;
      _valueController.text = attrValues[index].value;
    });
  }

  Future<void> _confirmDelete(int index, List<AttrValue> attrValues) async {
    final attrValue = attrValues[index];
    final bool? confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除规格值 "${attrValue.value}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      await _deleteAttrValue(index, attrValues);
    }
  }

  Future<void> _deleteAttrValue(int index, List<AttrValue> attrValues) async {
    try {
      final attrValueToDelete = attrValues[index];
      await ref.read(attrValueServiceProvider).deleteAttrValue(attrValueToDelete.id!);
      _refreshAttrValues();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('删除成功'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败：$e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  Future<void> _saveEdit(List<AttrValue> attrValues) async {
    final newValue = _valueController.text.trim();
    print('DEBUG: 保存编辑，newValue: "$newValue", isAdding: $isAdding');
    
    if (newValue.isEmpty || newValue.length > 20) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(newValue.isEmpty ? '规格值不能为空！' : '规格值不能超过20个字！')),
      );
      return;
    }

    try {
      if (isAdding) {
        print('DEBUG: 创建新规格值');
        final attrValueData = AttrValueData(
          value: newValue,
          attrNameId: widget.attrName.id!,
        );
        await ref.read(attrValueServiceProvider).createAttrValue(attrValueData);
        _refreshAttrValues();
      } else {
        final attrValueToUpdate = attrValues[editingIndex!];
        print('DEBUG: 更新规格值，id: ${attrValueToUpdate.id}, oldValue: ${attrValueToUpdate.value}, newValue: $newValue');
        await ref.read(attrValueServiceProvider).updateAttrValue(
          attrValueToUpdate.id!,
          newValue,
        );
        _refreshAttrValues();
      }
      setState(() {
        isEditing = false;
        editingIndex = null;
        isAdding = false;
        _valueController.clear();
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存失败：$e'), backgroundColor: Colors.red),
      );
    }
  }

  void _cancelEdit() {
    setState(() {
      isAdding = false;
      isEditing = false;
      editingIndex = null;
      _valueController.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
          tooltip: '返回',
        ),
        title: Text('${widget.attrName.name} - 规格值管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _refreshAttrValues,
            tooltip: '刷新',
          ),
        ],
      ),
      bottomNavigationBar: isAdding || isEditing
          ? null
          : Container(
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Theme.of(context).scaffoldBackgroundColor,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: SafeArea(
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: () {
                      print('DEBUG: 添加规格值按钮被点击');
                      if (!isEditing) {
                        _startAdding();
                      }
                    },
                    icon: const Icon(Icons.add),
                    label: const Text('添加规格值'),
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
              ),
            ),
      body: FutureBuilder<List<AttrValue>>(
        future: _attrValuesFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            print('DEBUG: 规格值数据加载失败: ${snapshot.error}');
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('加载失败: ${snapshot.error}'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: _refreshAttrValues,
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          final attrValues = snapshot.data ?? [];
          print('DEBUG: 获取到 ${attrValues.length} 个规格值');

          if (attrValues.isEmpty && !isAdding) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.label_outline,
                    size: 64,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '暂无规格值数据',
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '点击右下角"+"按钮来创建规格值',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[500],
                    ),
                  ),
                ],
              ),
            );
          }

          print('DEBUG: 构建ListView, isAdding: $isAdding, attrValues.length: ${attrValues.length}');
          return Padding(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).padding.bottom + 80, // 为FAB留出空间
            ),
            child: ListView.builder(
              itemCount: isAdding ? attrValues.length + 1 : attrValues.length,
              itemBuilder: (context, index) {
                print('DEBUG: 构建item $index');
                if (isAdding && index == 0) {
                  return ListTile(
                    title: TextField(
                      controller: _valueController,
                      decoration: const InputDecoration(
                        hintText: '请输入规格值',
                        border: OutlineInputBorder(),
                      ),
                    ),
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.save),
                          onPressed: () => _saveEdit(attrValues),
                        ),
                        IconButton(
                          icon: const Icon(Icons.cancel),
                          onPressed: _cancelEdit,
                        ),
                      ],
                    ),
                  );
                }

                final attrValueIndex = isAdding ? index - 1 : index;
                final attrValue = attrValues[attrValueIndex];

                return ListTile(
                  leading: Icon(
                    Icons.label,
                    color: Theme.of(context).primaryColor,
                  ),
                  title: isEditing && editingIndex == attrValueIndex
                      ? TextField(
                          controller: _valueController,
                          decoration: const InputDecoration(
                            hintText: '请输入规格值',
                            border: OutlineInputBorder(),
                          ),
                        )
                      : Text(attrValue.value),
                  trailing: isEditing && editingIndex == attrValueIndex
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.save),
                              onPressed: () => _saveEdit(attrValues),
                            ),
                            IconButton(
                              icon: const Icon(Icons.cancel),
                              onPressed: _cancelEdit,
                            ),
                          ],
                        )
                      : Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.delete),
                              onPressed: () => _confirmDelete(attrValueIndex, attrValues),
                              tooltip: '删除',
                            ),
                            IconButton(
                              icon: const Icon(Icons.edit),
                              onPressed: () => _startEditing(attrValueIndex, attrValues),
                              tooltip: '编辑',
                            ),
                          ],
                        ),
                );
              },
            ),
          );
        },
      ),
    );
  }
} 